package com.liuhangs.learning.crowd.webui.security.handle;

import com.google.gson.Gson;
import com.liuhangs.learning.crowd.util.ResponseUtils;
import com.liuhangs.learning.crowd.webui.bean.AdminResponse;
import com.liuhangs.learning.crowd.webui.bean.exception.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 11757
 * @DATE 2020/6/19
 */
public class FailureHandler implements AuthenticationFailureHandler {

    private static final Logger logger = LoggerFactory.getLogger(FailureHandler.class);
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException
    {
        AdminResponse result;
        if(e instanceof UsernameNotFoundException) {
            result = AdminResponse.fail(ErrorCode.NOT_EXIST_USER);
        } else if (e instanceof BadCredentialsException) {
            result = AdminResponse.fail(ErrorCode.ERROR_PWD);
        } else if (e instanceof LockedException) {
            result = AdminResponse.fail(ErrorCode.ACCOUNT_LOCK);
        } else if (e instanceof CredentialsExpiredException) {
            result = AdminResponse.fail(ErrorCode.TOKEN_INVALID);
        } else if (e instanceof AccountExpiredException) {
            result = AdminResponse.fail(ErrorCode.ACCOUNT_EXPIRED);
        } else if (e instanceof DisabledException) {
            result = AdminResponse.fail(ErrorCode.ACCOUNT_STOP);
        } else {
            result = AdminResponse.fail(ErrorCode.LOGIN_ERROR);
        }

        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());

        ResponseUtils.out(httpServletResponse, result);
    }
}
